package com.itmk.web.cart.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.cart.entity.Cart;
import com.itmk.web.cart.service.CartService;

import com.itmk.web.cart.entity.CartParm;
import com.itmk.web.goods.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    //加入移除收藏
    @PostMapping("/toggle")
    public ResultVo toggle(@RequestBody Cart cart) {
        // 1. 检查是否已在购物车
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Cart::getGoodsId, cart.getGoodsId())
                .eq(Cart::getUserId, cart.getUserId());

        Cart existingCart = cartService.getOne(queryWrapper);

        // 2. 如果已存在，则移除
        if (existingCart != null) {
            boolean isRemoved = cartService.removeById(existingCart.getCartId());
            if (isRemoved) {
                return ResultUtils.success("已从收藏移除");
            } else {
                return ResultUtils.error("移除失败，请重试");
            }
        }
        // 3. 如果不存在，则添加
        else {
            cart.setCreatedAt(new Date());
            boolean isSaved = cartService.save(cart);
            if (isSaved) {
                return ResultUtils.success("成功加入收藏");
            } else {
                return ResultUtils.error("加入收藏失败");
            }
        }
    }

    // 判断是否已添加到收藏
    @GetMapping("/isAdd")
    public ResultVo isAdd(@RequestParam Long goodsId, @RequestParam Long userId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Cart::getGoodsId, goodsId).eq(Cart::getUserId, userId);
        boolean exists = cartService.count(queryWrapper) > 0;
        return exists ? ResultUtils.success("已添加到收藏", 1) : ResultUtils.success("未添加到收藏", 0);
    }


    // 收藏页面根据userid生成瀑布流
    @GetMapping("/CartList")
    public ResultVo CartList(CartParm parm) {
        IPage<Goods> list = cartService.CartList(parm);
        return ResultUtils.success("get cartlist success", list);
    }
    // CartController.java 补充接口
    @PutMapping("/update")
    public ResultVo updateCart(@RequestBody Cart cart) {
        boolean isUpdated = cartService.updateById(cart);
        if (isUpdated) {
            return ResultUtils.success("更新成功");
        }
        return ResultUtils.error("更新失败");
    }

}
